package java_thinking.unit_17.clone;

import java.io.*;

/**
 * @Desc:   使用java.lang.Serializable来实现对象的深度克隆
 * @author: cww
 * @DateTime: 2019-04-27 15:39
 */

public class BeanUtil<T> {
    @SuppressWarnings("unchecked")
    public static <T> T cloneTo(T src) throws RuntimeException {
        ByteArrayOutputStream memoryBuffer = new ByteArrayOutputStream();
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        T dist = null;
        try {
            out = new ObjectOutputStream(memoryBuffer);
            out.writeObject(src);
            out.flush();
            in = new ObjectInputStream(new ByteArrayInputStream(memoryBuffer.toByteArray()));
            dist = (T) in.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (out != null)
                try {
                    out.close();
                    out = null;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            if (in != null)
                try {
                    in.close();
                    in = null;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
        }
        return dist;
    }

    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = BeanUtil.cloneTo(s1);
        System.out.println("s1 == s2 ? : " + (s1 == s2));
    }
}
